#! /usr/bin/python

# This is the main entry point to Plexus.  Well, probably.
# It has to handle all of the initialization tasks

# Then it has to instance all available APIs
# Then it must walk through the Plex, and instance all the listeners.
# Then, it waits.  For stuff.  To happen.  And things.

import os, sys, time

if sys.version_info < (2, 5):
	raise "Sorry, Plexus requires Python 2.6 or greater."

import plex

apidir = ''
listenerdir = ''
sharerdir = ''
modsdir = ''

# Setup the python path so that it points to the various module-containing directories
def setmodpaths():
	global modsdir
	modsdir = os.curdir + os.sep + "mods"	# Add directory of Plexus modules
	sys.path.append(modsdir)
	global apidir 
	apidir = os.curdir + os.sep + "apis"
	sys.path.append(apidir)					# Add directory of API modules
	global listenerdir 
	listenerdir = os.curdir + os.sep + "listeners"
	sys.path.append(listenerdir)			# Add directory of listener modules
	global sharerdir 
	sharerdir = os.curdir + os.sep + "sharers"
	sys.path.append(sharerdir)				# Add directory of sharer modules

def loadapis():
	# Go to the API directory and iterate through the files
	for root, dirs, files in os.walk(apidir):
		#print files
		for name in files:
			#print name[-3:]
			if (name[-3:] != ".py"):			# ignore anytyhing but the python source files!
				continue
			
			# Get ready for a bit of magic!
			tn = name.split(".")
			#print tn[0]
			apimod = None
			try: 
				apimod = __import__(tn[0])
				print("Loaded API module " + tn[0])
			except:
				print("FAILED TO LOAD API module " + tn[0])
				continue
				
			# And let's give it a kickstart...
			# In the general case, this starts the API on a separate thread.  Generally.
			apimod.APIStart(None)

def makelisteners():
	plexy = plex.Plexbase()			# Open up the database
	listenlist = plexy.get_listeners()		# Returns iteratable list of listeners
	for item in listenlist:
		#print item[1]
		
		# Alrighty, now lets import modules for each of these listeners
		# And if that works, let's instance a task for each of them.
		ln = 'plexus-listener-' + item[1]
		print ln
		listenmod = None
		try:
			listenmod = __import__(ln)
			print("Loaded listener module " + ln)
		except:
			# Interestingly, if we fail here because we couldn't find the module
			# We should probably go out to the authorized module storage thingy and grab it.
			# But that's for later.
			print("FAILED TO LOAD listener module " + ln)
			continue
		
		# Now let's try to get the listener to do something interesting
		# Which, of course, varies based on the listener
		listenmod.instance(item)
		
	plexy.close()


if __name__ == '__main__':
	print('Plexus starting up...')
	setmodpaths()				# Setup the module paths	
	#print(sys.path)
	print ('Loading API modules...')
	loadapis()					# Load all of the available API modules
	print('API modules loaded.')
	print('Instancing listeners...')
	makelisteners()
	print('Listeners made.')
	
	# Main event loop.  Which kinda doesn't do anything but wait for ^C
	while True:
		try:
			time.sleep(.1)
		except KeyboardInterrupt:
			print("\n\nExiting Plexus...")
			# Eventually we will want to clean up all of our threads.  But not yet.
			os._exit(0)